package game;

import java.util.Observable;

/**
 * Board class for board in game.
 * @author Natchanon Hongladaromp
 *
 */
public class Board extends Observable
{
	private int index1;
	private int index2;
	private String operation;
	private Game game;

	/**
	 * Construct for a board.
	 * @param game game for this board
	 */
	public Board(Game game)
	{
		this.game = game;
		index1 = -1;
		index2 = -1;
		operation = "";
	}

	/**
	 * Add a number to the board
	 * @param index index of number in list
	 * @return true if number can added
	 */
	public boolean addNumber(int index)
	{

		boolean result = false;
		if(index1 == -1)
		{
			index1 = index;
			result = true;
			setChanged();
			notifyObservers(UpdateType.UPDATE_BOARD);
		}
		else if(index2 == -1 && index != index1)
		{
			index2 = index;
			result = true;
			setChanged();
			notifyObservers(UpdateType.UPDATE_BOARD);
		}
		
		else if(index == index1)
		{
			index1 = -1;
			result = true;
			setChanged();
			notifyObservers(UpdateType.UPDATE_BOARD);
		}
		
		else if(index == index2)
		{
			index2= -1;
			result = true;
			setChanged();
			notifyObservers(UpdateType.UPDATE_BOARD);
		}

		return result;
	}

	/**
	 * Removes number form board.
	 * @param index index of number in list
	 * @return true if number can removed
	 */
	public boolean removeNumber(int index)
	{
		boolean result = false;
		if(index1 == index)
		{
			index1 = -1;
			result = true;
		}
		else if(index2 == index)
		{
			index2 = -1;
			result = true;
		}
		setChanged();
		notifyObservers(UpdateType.UPDATE_BOARD);
		return result;
	}

	/**
	 * Sets operation form this board.
	 * @param operation operation to set
	 * @return true if operation can added
	 */
	public boolean setOperator(String operation)
	{
		boolean result = false;
		if(!this.operation.equals(operation))
		{
			this.operation = operation;
			result = true;
		}
		setChanged();
		notifyObservers(UpdateType.UPDATE_BOARD);

		return result;
	}

	/**
	 * Calculate this board.
	 */
	public void calculate()
	{
		if(index1 != -1 && index2 != -1 && !operation.equals(""))
		{
			game.calculate(index1, index2, operation);

			reset();
		}
	}

	/**
	 * Returns numbers and operation on this borad.
	 * @return numbers and operation on this borad.
	 */
	public String[] getBoard()
	{
		String[] result = new String[3];

		result[0] = (index1 != -1)? String.format("%.0f ",game.getTree().get(index1).value()):"";
		result[1] = operation;
		result[2] = (index2 != -1)? String.format(" %.0f",game.getTree().get(index2).value()):"";

		return result;
	}
	
	/**
	 * Resets this borad.
	 */
	public void reset()
	{
		index1 = -1;
		index2 = -1;
		operation = "";
		setChanged();
		notifyObservers(UpdateType.UPDATE_BOARD);
	}
}
